<script setup lang="ts">
import { ref, onMounted, onUnmounted,nextTick } from 'vue'
import $ from 'jquery'
import {
    SrsRtcPublisherAsync,
    SrsRtcPlayerAsync,
    SrsError,
    SrsRtcFormatSenders
} from '../../assets/utils/hh'
import { log } from 'console';

onMounted(() => {
    // sseServiceOpen()
    arrr.value.forEach((el:any,index:number)=>{
        console.log(el);
        el.ref = 'meetVideoRef' + index
    })
    console.log('arrrarrrarrrarrr',arrr);

   
    

})

nextTick(() => {
   
});


onUnmounted(() => {


    // sseService.disconnect()
})
const arrr = ref<any>([
        {  l: "webrtc://216.fdmf.com:1990/meeting/b82bd4161ae0ff5f/0004" },
        {  l: "webrtc://216.fdmf.com:1990/meeting/b82bd4161ae0ff5f/0005" },
        {  l: "webrtc://216.fdmf.com:1990/meeting/b82bd4161ae0ff5f/0006" },
    ])
const layerPullRef2: any = ref(null)
const layerPullRef3: any = ref(null)

const playerPushRef: any = ref(null)
const layerPullRef: any = ref(null)
const videoRef = ref<any>(null)

const sdk_push: any = ref(null)
const sdk_pull: any = ref(null)
const sdk_push1: any = ref(null)
const sdk_pull1: any = ref(null)

function startPull() {
    $('#rtc_media_player_pull').show();
    console.log('pull111', sdk_pull.value);

    // Close PC when user replay.
    if (sdk_pull.value) {
        sdk_pull.value.close();
    }
    sdk_pull.value = SrsRtcPlayerAsync();
    console.log('pull222222222', sdk_pull.value);
    // https://webrtc.org/getting-started/remote-streams
    $('#rtc_media_player_pull').prop('srcObject', sdk_pull.value.stream);
    // Optional callback, SDK will add track to stream.
    // sdk.ontrack = function (event) { console.log('Got track', event); sdk.stream.addTrack(event.track); };

    // For example: webrtc://r.ossrs.net/live/livestream
    // var url = $("#txt_url").val();
    var url = "webrtc://216.fdmf.com:1990/meeting/83c14dbb064c9287/0001";
    sdk_pull.value.play(url).then(function (session: any) {
        console.log('session', session);
        console.log('session----', sdk_pull.value);
        // $('#sessionid').html(session.sessionid);
        // $('#simulator-drop').attr('href', session.simulator + '?drop=1&username=' + session.sessionid);
    }).catch(function (reason: any) {
        sdk_pull.value.close();
        // $('#rtc_media_player_pull').hide();
        console.error(reason);
    });
};
function startPush() {
    // $('#rtc_media_player_push').show();

    // Close PC when user replay.
    if (sdk_push.value) {
        sdk_push.value.close();
    }
    sdk_push.value = SrsRtcPublisherAsync();

    // User should set the stream when publish is done, @see https://webrtc.org/getting-started/media-devices
    // However SRS SDK provides a consist API like https://webrtc.org/getting-started/remote-streams
    $('#rtc_media_player_push').prop('srcObject', sdk_push.value.stream);
    // Optional callback, SDK will add track to stream.
    // sdk.ontrack = function (event) { console.log('Got track', event); sdk.stream.addTrack(event.track); };

    // https://developer.mozilla.org/en-US/docs/Web/Media/Formats/WebRTC_codecs#getting_the_supported_codecs
    sdk_push.value.pc.onicegatheringstatechange = function () {
        if (sdk_push.value.pc.iceGatheringState === "complete") {
            // $('#acodecs').html(SrsRtcFormatSenders(sdk_push.value.pc.getSenders(), "audio"));
            // $('#vcodecs').html(SrsRtcFormatSenders(sdk_push.value.pc.getSenders(), "video"));
        }
    };

    // For example: webrtc://r.ossrs.net/live/livestream
    var url = "webrtc://216.fdmf.com:1990/meeting/83c14dbb064c9287/0005";
    // var url = $("#txt_url").val();
    sdk_push.value.publish(url).then(function (session: any) {
        console.log('session-push', session);
        // $('#sessionid').html(session.sessionid);
        // $('#simulator-drop').attr('href', session.simulator + '?drop=1&username=' + session.sessionid);
    }).catch(function (reason: any) {
        // Throw by sdk.
        // if (reason instanceof SrsError) {
        //     if (reason.name === 'HttpsRequiredError') {
        //         alert(`WebRTC推流必须是HTTPS或者localhost：${reason.name} ${reason.message}`);
        //     } else {
        //         alert(`${reason.name} ${reason.message}`);
        //     }
        // }
        // // See https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#exceptions
        // if (reason instanceof DOMException) {
        //     if (reason.name === 'NotFoundError') {
        //         alert(`找不到麦克风和摄像头设备：getUserMedia ${reason.name} ${reason.message}`);
        //     } else if (reason.name === 'NotAllowedError') {
        //         alert(`你禁止了网页访问摄像头和麦克风：getUserMedia ${reason.name} ${reason.message}`);
        //     } else if (['AbortError', 'NotAllowedError', 'NotFoundError', 'NotReadableError', 'OverconstrainedError', 'SecurityError', 'TypeError'].includes(reason.name)) {
        //         alert(`getUserMedia ${reason.name} ${reason.message}`);
        //     }
        // }

        sdk_push.value.close();
        // $('#rtc_media_player_push').hide();
        console.error(reason);
    });
}

// ---------------------------------------------------------
function startPull1() {
    // $('#rtc_media_player_pull').show();
    console.log('startPull1-1111111', sdk_pull1.value);
    // Close PC when user replay.
    if (sdk_pull1.value) {
        sdk_pull1.value.close();
    }
    sdk_pull1.value = SrsRtcPlayerAsync();

    console.log('startPull1-2222222', sdk_pull1.value);

    $('#rtc_media_player_pull').prop('srcObject', sdk_pull.value.stream);
    var url = "webrtc://216.fdmf.com:1990/meeting/4da7ccbd5ccbc088/0003";
    sdk_pull1.value.play(url).then(function (session: any) {
        console.log('startPull1session', session);
        layerPullRef.value.srcObject = sdk_pull1.value.stream
        // $('#sessionid').html(session.sessionid);
        // $('#simulator-drop').attr('href', session.simulator + '?drop=1&username=' + session.sessionid);
        console.log(sdk_pull1.value);


    }).catch(function (reason: any) {
        sdk_pull1.value.close();
        // $('#rtc_media_player_pull').hide();
        console.error(reason);
    });
};
function startPush1() {


    // Close PC when user replay.
    if (sdk_push1.value) {
        sdk_push1.value.close();
    }
    sdk_push1.value = SrsRtcPublisherAsync();

    playerPushRef.value.srcObject = sdk_push1.value.stream
    sdk_push1.value.pc.onicegatheringstatechange = function () {
        if (sdk_push1.value.pc.iceGatheringState === "complete") {
            // $('#acodecs').html(SrsRtcFormatSenders(sdk_push.value.pc.getSenders(), "audio"));
            // $('#vcodecs').html(SrsRtcFormatSenders(sdk_push.value.pc.getSenders(), "video"));
        }
    };

    // For example: webrtc://r.ossrs.net/live/livestream
    var url = "webrtc://216.fdmf.com:1990/live/livestream";
    // var url = $("#txt_url").val();
    sdk_push1.value.publish(url).then(function (session: any) {
        console.log('session-push1111', session);
        // $('#sessionid').html(session.sessionid);
        // $('#simulator-drop').attr('href', session.simulator + '?drop=1&username=' + session.sessionid);
    }).catch(function (reason: any) {
        // Throw by sdk.
        if (reason instanceof SrsError) {
            if (reason.name === 'HttpsRequiredError') {
                alert(`WebRTC推流必须是HTTPS或者localhost：${reason.name} ${reason.message}`);
            } else {
                alert(`${reason.name} ${reason.message}`);
            }
        }
        // See https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#exceptions
        if (reason instanceof DOMException) {
            if (reason.name === 'NotFoundError') {
                alert(`找不到麦克风和摄像头设备：getUserMedia ${reason.name} ${reason.message}`);
            } else if (reason.name === 'NotAllowedError') {
                alert(`你禁止了网页访问摄像头和麦克风：getUserMedia ${reason.name} ${reason.message}`);
            } else if (['AbortError', 'NotAllowedError', 'NotFoundError', 'NotReadableError', 'OverconstrainedError', 'SecurityError', 'TypeError'].includes(reason.name)) {
                alert(`getUserMedia ${reason.name} ${reason.message}`);
            }
        }

        sdk_push1.value.close();
        $('#rtc_media_player_push').hide();
        console.error(reason);
    });
}




function btnPull() {
    console.log('btn_pullbtn_pullbtn_pullbtn_pull');
    startPull();
}
function btnPublish() {
    console.log('btn_publishbtn_publishbtn_publish');
    startPush();
}
function btnPull11() {
    console.log('11111111');
    startPull1();
}
function btnPublish11() {
    console.log('222222222');
    startPush1();
}


const pull1: any = ref(null)
function btnPull333() {
    console.log('11111111');


   for (let index = 0; index < arrr.value.length; index++) {
        const el = arrr.value[index]
        // el.ref = 'meetVideoRef' + index
        // el.class = 'meet_video' + index

      

        // pull1.value = SrsRtcPlayerAsync();

        let url = el.l;
        startPull123(url,index)
        // pull1.value.play(url).then(function (session: any) {
        //     layerPullRef2.value.srcObject = pull1.value.stream
        //     layerPullRef3.value.srcObject = pull1.value.stream
        //     // meetListref.value.forEach((e: any) => {
        //     //     console.log(e);layerPullRef.value.srcObject = sdk_pull1.value.stream
        //     //     console.log(e.querySelector('video'));
        //     //     // e.querySelector('.meet_video').srcObject = null
        //     //     // e.querySelector('video').IN= 'jkdjdj'
        //     //     e.querySelector('video').srcObject =  arrr.value[index].liu.stream
        //     // })
        // }).catch(function (reason: any) {
        //     pull1.value.close();
        //     console.error(reason);
        // });
 


    }
    console.log('skadsjkadsjkladshjkl', arrr.value);


    // startPull123();
}

function btnPull444() {
    let  box:any =  document.getElementById('videoRef')  
    arrr.value.forEach((el:any,index:number)=>{
        console.log(el);
       let id = '#'+ 'meetVideoRef'+index
        pull1.value = SrsRtcPlayerAsync();
        box.querySelector(id).srcObject = pull1.value.stream
        
        
        
        
        let url = el.l;
        pull1.value.play(url).then(function (session: any) {
            // el.ref.srcObject = pull1.value.stream
 
        }).catch(function (reason: any) {
            pull1.value.close();
            console.error(reason);
        });

    })
   
}



function startPull123(url:any,index:any) {
    console.log(url,index);
    
    pull1.value = SrsRtcPlayerAsync();
    // let url = el.l;
    if (index == 0) {
            layerPullRef2.value.srcObject = pull1.value.stream
        }
        if (index == 1) {
            layerPullRef3.value.srcObject = pull1.value.stream
        }
    pull1.value.play(url).then(function (session: any) {
       
       
        // meetListref.value.forEach((e: any) => {
        //     console.log(e);layerPullRef.value.srcObject = sdk_pull1.value.stream
        //     console.log(e.querySelector('video'));
        //     // e.querySelector('.meet_video').srcObject = null
        //     // e.querySelector('video').IN= 'jkdjdj'
        //     e.querySelector('video').srcObject =  arrr.value[index].liu.stream
        // })
    }).catch(function (reason: any) {
        pull1.value.close();
        console.error(reason);
    });

};

</script>
<template>
    <div class="content">
        <div class="box">
            <button class="btn btn-primary" id="btn_publish" @click="btnPublish">推流</button>
            <video class="video" id="rtc_media_player_push" controls autoplay></video>
        </div>
        <div class="box">
            <button class="btn btn-primary" id="btn_pull" @click="btnPull">拉流</button>
            <video class="video" id="rtc_media_player_pull" controls autoplay></video>
        </div>
        <div>
            <!-- <div class="box">
                <button class="btn btn-primary"  @click="btnPublish11">推流11</button>
                <video class="video" ref="playerPushRef" controls autoplay></video>
            </div> -->
            <div class="box">
                <button class="btn btn-primary" @click="btnPull11">拉流11</button>
                <video class="video" ref="layerPullRef" controls autoplay></video>
            </div>



            <div class="box">
                <button class="btn btn-primary" @click="btnPull333">拉流11btnPull333</button>
                <video class="video11" ref="layerPullRef2" controls autoplay ></video>
                <video class="video11" ref="layerPullRef3" controls autoplay></video>
            </div>



            <div class="box"  id="videoRef">
                <button class="btn btn-primary" @click="btnPull444">拉流11btnPull444</button>

                <video v-bind:id="n.ref"  v-bind:ref="n.ref"   class="video11"  controls autoplay v-for="(n,k) in arrr" :key="k" ></video>

                
               
            </div>



        </div>
    </div>
</template>
<style>
#rtc_media_player {
    margin: 10px 0 0 0;
}

.video {
    width: 100%;
    height: 600px;
}

.content {
    display: flex;
    flex-flow: row nowrap;
}

.box {
    margin: 0 2px;
    width: 50%;
    display: flex;
    flex-flow: column nowrap;
}

.btn {
    margin: 0 0 10px 0;
    padding: 10px 20px;
    font-weight: bold;
    font-size: 20px;
}
</style>
